package ${package}.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 验证码校验
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Component
@AllArgsConstructor
public class CaptchaFilter extends OncePerRequestFilter implements InitializingBean {

    private final StringRedisTemplate redisTemplate;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 只在登录时对验证码进行拦截,验证
     */
    private static final String URL = "/oauth/token";

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=utf-8");
        if (antPathMatcher.match(URL, request.getRequestURI()) && "POST".equals(request.getMethod())) {
            String msg = checkImageCode(request);
            if (!StringUtils.isEmpty(msg)) {
                ObjectMapper mapper = new ObjectMapper();
                response.setContentType("application/json");
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
                response.getWriter().write(mapper.writeValueAsString(Result.error(msg)));
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 校验验证码是否正确
     *
     * @param request
     */
    private String checkImageCode(HttpServletRequest request) {

        String uuid = request.getHeader("uuid");
        /*获取图片验证码与redis验证*/
        String imageCode = request.getHeader("code");

        String redisImageCode = redisTemplate.opsForValue().get("captcha_codes:" + uuid);
        /*redis的验证码不能为空*/
        if (StringUtils.isEmpty(redisImageCode) || StringUtils.isEmpty(imageCode)) {
            return "验证码不能为空";
        }
        /*校验验证码*/
        if (!imageCode.equalsIgnoreCase(redisImageCode)) {
            return "验证码错误";
        }
        redisTemplate.delete("captcha_codes:" + uuid);
        return null;
    }
}
